package com.zhaoyan.okgorxjavademo;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;


import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;


class JeckInterceptor implements Interceptor {
    public static final Charset UTF8 = Charset.forName("UTF-8");
    private BaseEntity apiResult;

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        Response response = chain.proceed(request);
        ResponseBody responseBody = response.body();
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();
        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }
        String bodyString = buffer.clone().readString(charset);
        Log.d("123", "网络拦截器:" + bodyString + " host:" + request.url().toString());
        boolean isText = isText(contentType);
        if (!isText) {
            return response;
        }
        //判断响应是否过期（无效）
        if (isResponseExpired(response, bodyString)) {

            //同步请求方式，获取最新的Token
//            String newSession = getNewToken();
//            if (newSession.equals("重新登录")) {
//                response.body().close();
//                return response;
//            }
            //String newSession = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJzZXJ2ZXIiLCJzdWIiOiJBbGwiLCJhdWQiOiJjbGllbnQiLCJleHAiOjE1MDg3NTQxMDUsImlhdCI6MTUwODc0NjkwNSwianRpIjoiNjkwNSIsInJlc2V0IjoxNTA4NzU0NzA1LCJ1c2VyX2lkIjozfQ.ZZjm_Rr4ysnF2WSW2rnZCmvGgTN3ej2AB_o6Ph4Wq44";
            //使用新的Token，创建新的请求
            String key = "token";
            // create a new request and modify it accordingly using the new token
            String method = request.method();
            if (request.body() instanceof FormBody) {
                FormBody oldBody = (FormBody) request.body();
                Log.e("1231", "------>123123");
                if (oldBody == null) {
                    if (method.equalsIgnoreCase("GET")) {
                        oldBody = getRequestParams(request.url().query());
                    } else {
                        return chain.proceed(request);
                    }
                }
                FormBody.Builder newBody = new FormBody.Builder();
                for (int i = 0; i < oldBody.size(); i++) {
                    String name = oldBody.encodedName(i);
                    String value = oldBody.encodedValue(i);
                    if (!TextUtils.isEmpty(name)) {
                        if (name.equals(key)) {
//                            value = newSession;
                        }

                    }
                    newBody.add(name, value);
                }


                Request newRequest;
                if (method.equalsIgnoreCase("GET")) {
                    String url = packageParams(newBody.build());
                    HttpUrl newHrrpIrl = request.url().newBuilder().query(url).build();
                    newRequest = request.newBuilder().url(newHrrpIrl).get().build();

                } else {
                    newRequest = request.newBuilder().post(newBody.build()).build();

                }
                return chain.proceed(newRequest);
            } else {
                return response;
            }
        } else {
            return response;
        }

    }

    private boolean isText(MediaType mediaType) {
        if (mediaType == null)
            return false;
        if (mediaType.type() != null && mediaType.type().equals("text")) {
            return true;
        }
        if (mediaType.subtype() != null) {
            if (mediaType.subtype().equals("json")) {
                return true;
            }
        }
        return false;
    }

    /**
     * 根据Response，判断Token是否失效
     *
     * @param response
     * @return
     */
    public boolean isResponseExpired(Response response, String bodyString) {
        apiResult = new Gson().fromJson(bodyString, BaseEntity.class);
        Log.d("123", "isResponseExpired: " + apiResult.isSuccess());
        if (apiResult != null) {
            boolean code = apiResult.isSuccess();
            if (code) {
                return true;
            }
        }
        return false;
    }

    /**
     * 同步请求方式，获取最新的Token
     *
     * @return
     */

//    public static String getNewToken() throws IOException {
//
//        String tokenDate;
//        //手动创建一个OkHttpClient并设置超时时间
//        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
//        httpClientBuilder.connectTimeout(1000, TimeUnit.SECONDS);
//
//        String code;
//        /**
//         *  拦截器
//         */
//        httpClientBuilder.addInterceptor(chain -> {
//            Request request = chain.request();
//
//            HttpUrl.Builder authorizedUrlBuilder = request.url()
//                    .newBuilder();
//
//            Request newRequest = request.newBuilder()
//                    //对所有请求添加请求头
//                    //.header("mobileFlag", "adfsaeefe").addHeader("type", "4")
//                    .method(request.method(), request.body())
//                    .url(authorizedUrlBuilder.build())
//                    .build();
//
//            return chain.proceed(newRequest);
//        });
//
//        Retrofit retrofit = new Retrofit.Builder()
//                .client(httpClientBuilder.build())
//                .addConverterFactory(GsonConverterFactory.create())
//                .baseUrl(Api.BASE_URL)
//                .build();
//        ;
//        BaseJson<TokenEntity> token = retrofit.create(PublicService.class)
//                .getToken((String) PrefUtils.get(BaseApplication.context, "token", ""))
//                .execute()
//                .body();
//        code = token.getCode();
//        if (code.equals("2")) {
//            PrefUtils.put(BaseApplication.context, "isLogin", false);
//            Intent intent = new Intent(BaseApplication.context, StartActivity.class);
//            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            BaseApplication.context.startActivity(intent);
//            return "重新登录";
//
//        } else {
//            tokenDate = token.getData().token;
//            //将token转换
//            PrefUtils.put(BaseApplication.context, "token", tokenDate);
//            Log.e("123123", "--------------->222");
//            return tokenDate;
//        }
//    }

    /**
     * 将GET请求的参数封装成FormBody
     */
    private FormBody getRequestParams(String params) {
        if (params == null)
            return null;
        String[] strArr = params.split("&");
        if (strArr == null) {
            return null;
        }

        TreeMap<String, String> map = new TreeMap<>();
        FormBody.Builder fBulder = new FormBody.Builder();
        for (String s : strArr) {
            String[] sArr = s.split("=");
            if (sArr.length < 2)
                continue;
            map.put(sArr[0], sArr[1]);
            fBulder.add(sArr[0], sArr[1]);
        }
        FormBody formBody = fBulder.build();
        return formBody;
    }


    /**
     * 封装参数
     */
    private String packageParams(FormBody oldBody) {
        List<String> namesAndValues = new ArrayList<>();
        for (int i = 0; i < oldBody.size(); i++) {
            String name = oldBody.encodedName(i);
            String value = oldBody.encodedValue(i);
            if (!TextUtils.isEmpty(name)) {
                namesAndValues.add(name);
                namesAndValues.add(value);
            }
        }
        StringBuilder sb = new StringBuilder();
        namesAndValuesToQueryString(sb, namesAndValues);
        return sb.toString();
    }

    /**
     * 合并GET参数
     */
    private void namesAndValuesToQueryString(StringBuilder out, List<String> namesAndValues) {
        for (int i = 0, size = namesAndValues.size(); i < size; i += 2) {
            String name = namesAndValues.get(i);
            String value = namesAndValues.get(i + 1);
            if (i > 0) out.append('&');
            out.append(name);
            if (value != null) {
                out.append('=');
                out.append(value);
            }
        }
    }
}
